<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

/**
 * Class Staff.
 *
 * @package namespace App\Models;
 */
class Staff extends BaseModel implements Transformable
{
    use TransformableTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['company_id', 'dorm_id', 'staff_position_id', 'is_fee_bearer', 'department_id', 'name', 'card_num', 'id_card', 'age', 'sex', 'phone', 'status', 'remark', 'latest_in_date', 'date_enroll'];
    protected $appends = ['staffInfo'];

    public function dorm()
    {
        return $this->belongsTo(Dorm::class);
    }

    public function department()
    {
        return $this->belongsTo(Department::class);
    }

    public function staffPosition()
    {
        return $this->belongsTo(StaffPosition::class);
    }

    public function couple()
    {
        return $this->belongsTo(Staff::class, 'couple_id');
    }

    public function families()
    {
        return $this->hasMany(Family::class);
    }

    public function staffDormAdjusts()
    {
        return $this->hasMany(StaffDormAdjust::class)->orderBy('adjust_date', 'desc')->orderBy('created_at', 'desc');
    }

    public function getStaffInfoAttribute()
    {
        $sex =   $this->sex ? ($this->sex == 1 ? '男' : '女') : '';

        return optional($this->department)->name . " " . optional($this->staffPosition)->position . " " . $this->name . " " . $sex;
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (auth()->check()) {
                $model->company_id = auth()->user()->company_id ?? null;
            }
        });
    }
}
